import { Injectable } from '@nestjs/common';
import ffmpeg from 'fluent-ffmpeg';
import path from 'path';
import { unlink } from 'fs/promises';
const { VodUploadClient, VodUploadRequest } = require('vod-node-sdk');
const SECOND = 1000;
const MINUTE = 60 * SECOND;
const HOUR = 60 * MINUTE;
const DAY = 24 * HOUR;
@Injectable()
export class UploadService {
  async extractFirstFrame(
    videoPath: string,
    outputPath: string,
  ): Promise<void> {
    return new Promise((resolve, reject) => {
      ffmpeg(videoPath)
        .on('filenames', function (filenames) {
          console.log('Will generate ' + filenames.join(', '));
        })

        .on('end', function (data) {
          console.log('Screenshots taken', data);
          resolve();
        })
        .screenshots({
          timestamps: ['00:00.00'],
          count: 1,
          filename: 'test.jpg',
          folder: outputPath,
        });
    });
  }
  async getMetaData(videoPath: string, outputPath: string) {
    return new Promise((resolve, reject) => {
      ffmpeg.ffprobe(videoPath, (err, data) => {
        resolve(this.parseTimeData(data['format']?.duration * 1000));
      });
    });
  }
  parseTimeData(time) {
    const days = Math.floor(time / DAY);
    const hours = Math.floor((time % DAY) / HOUR);
    const minutes = Math.floor((time % HOUR) / MINUTE);
    const seconds = Math.floor((time % MINUTE) / SECOND);
    const milliseconds = Math.floor(time % SECOND);
    return {
      days,
      hours,
      minutes,
      seconds,
      milliseconds,
    };
  }

  async processVideoAndExtractThumbnail(videoPath: string): Promise<string> {
    const tempThumbnailPath = path.join(__dirname, '../../', 'static');
    await this.extractFirstFrame(videoPath, tempThumbnailPath);
    const time: any = await this.getMetaData(videoPath, tempThumbnailPath);
    console.log(time);

    const SecretId = 'AKIDVvAC9xlbIoDVecbVWRBk7JK6XyJRUM3X';
    const secretKey = 'McotmRu9AyYxRp4yiPxJUEoKrEyd9Wr3';
    const client = new VodUploadClient(SecretId, secretKey);
    let req = new VodUploadRequest();
    req.MediaFilePath = videoPath;
    req.CoverFilePath = path.join(tempThumbnailPath, 'test.jpg');
    return new Promise((resolve, reject) => {
      client.upload('ap-guangzhou', req, function (err, data) {
        if (err) {
        } else {
          unlink(videoPath);
          unlink(path.join(tempThumbnailPath, 'test.jpg'));
          resolve({
            ...data,
            duration: `${time.hours}`,
          });
        }
      });
    });
  }
}
